<template>
    <el-button plain @click="openCreateForm()">
        添加新的交易信息
    </el-button>
    <div style="display: flex; flex-direction: column;width: 100%;">
        <el-table :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" stripe
            :default-sort="{ prop: 'operateTime', order: 'descending' }" style="width: 100%">
            <el-table-column prop="operateTime" sortable :label="$t('operateTime')" />
            <el-table-column prop="fundName" :label="$t('fundName')" />
            <el-table-column prop="operateType" :label="$t('operateType')" />
            <el-table-column prop="operateMoney" sortable :label="$t('operateMoney')" />
            <el-table-column align="right">
                <template #header>
                    <el-input @keyup.enter.native="handleSearch()" v-model="keyword" size="small"
                        placeholder="Type to search" />
                </template>
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">
                        Edit
                    </el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button size="small" type="danger">Delete</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @current-change="handleCurrentChange" :page-size="pageSize"
            layout="total,prev, pager, next" :total="tableData.length">
        </el-pagination>
    </div>

    <!-- 创建新的定投信息 -->
    <el-dialog v-model="createInfoVisible" title="创建新的定投信息" width="500">
        <el-form :model="form">
            <el-form-item label="基金名称" :label-width="formLabelWidth">
                <el-select value-key="fundCode" v-model="form.fund" placeholder="请选择基金">
                    <el-option v-for="item in funds" :key="item.fundCode" :label="item.fundName" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item label="交易类型" :label-width="formLabelWidth">
                <el-select v-model="form.operateType" placeholder="请选择交易类型">
                    <el-option label="定投" value="定投" />
                    <el-option label="赎回" value="赎回" />
                </el-select>
            </el-form-item>
            <el-form-item label="交易金额" :label-width="formLabelWidth">
                <el-input v-model="form.operateMoney" autocomplete="off" />
            </el-form-item>
            <el-form-item label="交易日期" :label-width="formLabelWidth">
                <el-date-picker value-format="YYYY-MM-DD" v-model="form.operateTime" type="date"
                    placeholder="Pick a day" :shortcuts="shortcuts" size="default" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="createInfoVisible = false">{{ $t('cancel') }}</el-button>
                <el-button type="primary" @click="createInfo()">
                    {{ $t('submit') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改定投信息 -->
    <el-dialog v-model="updateInfoVisible" title="修改定投信息" width="500">
        <el-form :model="updateForm">
            <el-form-item label="基金号码" :label-width="formLabelWidth">
                <el-input disabled v-model="updateForm.fundCode" autocomplete="off" />
            </el-form-item>
            <el-form-item label="基金名称" :label-width="formLabelWidth">
                <el-input disabled v-model="updateForm.fundName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="交易类型" :label-width="formLabelWidth">
                <el-select v-model="updateForm.operateType" placeholder="请选择交易类型">
                    <el-option label="定投" value="定投" />
                    <el-option label="赎回" value="赎回" />
                </el-select>
            </el-form-item>
            <el-form-item label="交易金额" :label-width="formLabelWidth">
                <el-input v-model="updateForm.operateMoney" autocomplete="off" />
            </el-form-item>
            <el-form-item label="交易日期" :label-width="formLabelWidth">
                <el-date-picker value-format="YYYY-MM-DD" v-model="updateForm.operateTime" type="date"
                    placeholder="Pick a day" :shortcuts="shortcuts" size="default" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updateInfoVisible = false">{{ $t('cancel') }}</el-button>
                <el-button type="primary" @click="updateInfo()">
                    {{ $t('submit') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import request from "../../utils/request";
import { ElMessage } from 'element-plus';
import { useI18n } from "vue-i18n"
const { t } = useI18n();

const createInfoVisible = ref(false)
const updateInfoVisible = ref(false)
const formLabelWidth = '140px'
// 当前页码
let currentPage = ref(1);
// 每页条数
let pageSize = 10;

const funds = ref<any[]>([])
//定义tableData
const tableData = ref<any[]>([]);
// 日期快捷选项
const shortcuts = [
    {
        text: '今天',
        value: new Date(),
    },
    {
        text: '昨天',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date
        },
    },
    {
        text: '一周前',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
        },
    },
]

const keyword = ref<string>('')

// 更新交易信息数据类型
interface updateFormInterface {
    id: number;
    fundCode: string;
    fundName: string;
    operateType: string;
    operateMoney: string;
    operateTime: string;
}

// 创建交易信息表单
const form = ref({
    fund: null,
    fundCode: '',
    fundName: '',
    operateType: '',
    operateMoney: '',
    operateTime: ''
})

// 更新交易信息表单
const updateForm = ref({
    id: 0,
    fundCode: '',
    fundName: '',
    operateType: '',
    operateMoney: '',
    operateTime: ''
})

// 模糊查询
const handleSearch = () => {
    request.post("/fund/v1/getFundListByKeyword/" + keyword.value).then(res => {
        if (res.data.code == 1) {
            ElMessage.success(res.data.msg);
            tableData.value = res.data.data;
        } else {
            ElMessage.error(res.data.msg);
        }
    }).catch(err => {
        console.log("Error>>", err);
        ElMessage.error(t('networkError'));
    });
}

/**
 * 修改交易信息
 * updateForm.value = row 这意味着updateForm.value 和 row 指向的是内存中的同一个对象
 * updateForm.value = { ...row } 实际上是创建了一个row对象的浅拷贝
 * updateForm.value 引用了与row相同的属性，但不是同一个对象。
 * @param row 点击的当前行数据
 */
const handleEdit = (row: updateFormInterface) => {
    // 打开对话框
    updateInfoVisible.value = true;
    updateForm.value = { ...row };
}

/**
 * 删除交易信息
 * @param index 被删除的交易信息id
 */
const handleDelete = (index: number) => {
    request.delete("/fund/v1/deleteInfoById/" + index).then(res => {
        if (res.data.code == 1) {
            ElMessage.success(res.data.msg);
            createInfoVisible.value = false;
            getTableData();
        } else {
            ElMessage.error(res.data.msg);
        }
    }).catch(err => {
        console.log("Error>>", err);
        ElMessage.error(t('networkError'));
    });
}

// 获取交易信息
const getTableData = () => {
    request.get("/fund/v1/getTableData").then(res => {
        if (res.data.code == 1) {
            tableData.value = res.data.data;
        } else {
            ElMessage.error(res.data.msg);
        }
    }).catch(err => {
        console.log("Error>>", err);
        ElMessage.error(t('networkError'));
    });
};

//打开创建表单
const openCreateForm = () => {
    createInfoVisible.value = true;
    request.get("/fund/v1/getFundsData").then(res => {
        if (res.data.code == 1) {
            funds.value = res.data.data;
        } else {
            ElMessage.error(res.data.msg);
        }
    }).catch(err => {
        console.log("Error>>", err);
        ElMessage.error(t('networkError'));
    });
}

// 创建新的定投信息
const createInfo = () => {
    // 预处理提交的表单
    form.value.fundCode = form.value.fund.fundCode;
    form.value.fundName = form.value.fund.fundName;

    request.post("/fund/v1/createInfo", form.value).then(res => {
        if (res.data.code == 1) {
            ElMessage.success(res.data.msg);
            createInfoVisible.value = false;
            getTableData();
        } else {
            ElMessage.error(res.data.msg);
        }
    }).catch(err => {
        console.log("Error>>", err);
        ElMessage.error(t('networkError'));
    });
}

// 更新、编辑交易信息
const updateInfo = () => {
    request.post("/fund/v1/updateInfo", updateForm.value).then(res => {
        if (res.data.code == 1) {
            ElMessage.success(res.data.msg);
            updateInfoVisible.value = false;
            getTableData();
        } else {
            ElMessage.error(res.data.msg);
        }
    }).catch(err => {
        console.log("Error>>", err);
        ElMessage.error(t('networkError'));
    });
}


/**
 * 实现翻页功能
 * @param clickPage 点击的页码
 */
const handleCurrentChange = (clickPage: number) => {
    currentPage.value = clickPage;
}

onMounted(() => {
    getTableData();
});
</script>